package com.yomahub.liteflow.example.threadproject;

import java.util.concurrent.*;

public class Demo1 {
    public static void main(String[] args) {



//        newcached();

//        newfixed();

//        newscheduled();

        newsingle();
    }

    public static void newcached(){
        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 1; i < 5; i++) {
            final int taskId = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    ThreadUtils.sleep(1000);

                    for (int j = 0; j < 4; j++) {

                        ThreadUtils.sleep(1000);
//
//                        findgetID() you
//                            continue;
//
//                        save();

                        System.out.println("第" + taskId + "个任务" + "第" + j + "次执行");

                    }
                }
            });
        }

        pool.shutdown();
    }

    /**
     * 最大并发是3，多出的一个线程，等待执行
     */
    public static void newfixed(){

        ExecutorService pool =  Executors.newFixedThreadPool(3);
        for (int i = 1; i < 5; i++) {
            final int taskId = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 4; j++) {

                        ThreadUtils.sleep(1000);

                        System.out.println("第" + taskId + "个任务" + "第" + j + "次执行");

                    }
                }
            });
        }
    }

    // 定时和周期行的执行任务
    public static void newscheduled(){
        ScheduledExecutorService pool =  Executors.newScheduledThreadPool(1);
        pool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("5秒后执行一次任务");
            }
        }, 5, TimeUnit.SECONDS);

        pool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("5s后执行第一次，以后每2s执行一次");
            }
        },5,2,TimeUnit.SECONDS);
    }

    // 单线程的线程池
    public static void newsingle(){
        ExecutorService pool =  Executors.newSingleThreadExecutor();
        for (int i = 1; i < 5; i++) {
            final int taskid = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int j = 1; j < 5; j++) {
                        System.out.println("第" + taskid + "个任务" + "第" + j + "次执行");
                    }

                }
            });

        }

        pool.shutdown();

    }
}
